<template>
  <div>
    <h5ve-dialog
      :title="title"
      :close-on-click-modal="false"
      :width="720"
      :isFooter="true"
      :show.sync="visible">
      <fd-generate-form
        v-if="visible"
        :edit="method !== 'view'"
        :data="options"
        :value="initData"
        v-loading="loading"
        :class="method==='view'?'readonly':''"
        ref="generateForm"
      >
      </fd-generate-form>
      <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="visible = false" icon="el-icon-circle-close">关闭</el-button>
          <el-button size="small" type="primary" v-if="method != 'view'" @click="doSubmit()" icon="el-icon-circle-check">确定</el-button>
        </span>
    </h5ve-dialog>
  </div>
</template>

<script>
import {getByCode, genByCode, saveGenerate} from '@/api/toolkit/pageInfo'

export default {
  components: {},
  data() {
    return {
      code: '',
      title: '',
      method: '',
      beanId: '',
      visible: false,
      loading: false,
      initData: {},
      dataBindMap: new Map(),
      options: {list: []}
    }
  },
  created() {
    this.createForm()
  },
  methods: {
    init(method, beanId) {
      console.log(beanId)
      this.method = method
      this.beanId = beanId
      this.initData = {}
      if (method === 'add') {
        this.title = `新建`
      } else if (method === 'edit') {
        this.title = '修改'
      } else if (method === 'view') {
        this.title = '查看'
      }
      this.visible = true
      this.loading = false
      this.$nextTick(() => {
        this.$refs.generateForm.reset()
        if (beanId) {
          this.loading = true
          genByCode({code: this.code, id: beanId}).then(({data}) => {
            this.loading = false
            console.log(data)
            for (let key in data) {
              let dataField = this.dataBindMap.get(key)
              if (dataField && (dataField['type'] === 'checkbox' ||
                dataField['type'] === 'imgupload' ||
                dataField['type'] === 'table' ||
                (dataField['type'] === 'select' && dataField.options.multiple) ||
                dataField['type'] === 'fileupload')) {
                if (data[key] && typeof data[key] === 'string') {
                  data[key] = JSON.parse(data[key])
                } else if (!data[key]) {
                  data[key] = []
                }
              }
              if (dataField && (dataField['type'] === 'number' || dataField['options'].dataType === 'number')) {
                if (data[key] !== undefined && data[key] !== '' && typeof data[key] === 'string') {
                  data[key] = JSON.parse(data[key])
                }
              }
            }
            this.initData = data
          })
        }
      })
    },
    generateModel(genList) {
      for (let i = 0; i < genList.length; i++) {
        if (genList[i].type === 'grid') {
          genList[i].columns.forEach(item => {
            this.generateModel(item.list)
          })
        } else if (genList[i].type === 'tabs') {
          genList[i].tabs.forEach(item => {
            this.generateModel(item.list)
          })
        } else {
          // 处理老版本没有dataBind值的情况，默认绑定数据
          if (genList[i].options.dataBind) {
            this.dataBindMap.set(genList[i].model, genList[i])
          }
        }
      }
    },
    createForm() {
      const {path} = this.$route;
      if (path.indexOf('generate') === -1) {
        // 不是动态表单不加载
        return;
      }
      const routeStr = path.split("/");
      this.code = routeStr[routeStr.length - 1];
      getByCode({code: this.code}).then(response => {
        if (response.data && response.data.pageData) {
          this.options = JSON.parse(response.data.pageData)
          this.genRemarks()
        } else {
          this.options = {
            'list': [],
            'config': {'labelWidth': 100, 'labelPosition': 'right', 'size': 'small', 'customClass': ''}
          }
        }
        this.dataBindMap.clear()
        this.generateModel(this.options.list)
      })
    },
    genRemarks(){
      this.options.list.push({
        "type": "textarea",
        "icon": "icon iconfont icon-diy-com-textarea",
        "dsId": "",
        "tableName": "",
        "primaryKey": "",
        "foreignKey": "",
        "options": {
          "width": "100%",
          "defaultValue": "",
          "required": false,
          "requiredMessage": "",
          "disabled": false,
          "pattern": "",
          "patternMessage": "",
          "placeholder": "请输入备注",
          "customClass": "",
          "labelWidth": 100,
          "isLabelWidth": false,
          "hidden": false,
          "dataBind": true,
          "fieldType": "varchar",
          "fieldLength": 255,
          "isAdd": true,
          "isSort": false,
          "editReadonly": false,
          "isModify": true,
          "isList": true,
          "isQuery": false,
          "isImport": true,
          "queryType": "eq",
          "javaType": "String",
          "remoteFunc": "func_1732607271043",
          "remoteOption": "option_1732607271043"
        },
        "name": "备注",
        "key": "1732607271043",
        "model": "remarks",
        "rules": []
      })
    },
    // 表单提交
    doSubmit() {
      // 自定义js ，保存前执行
      if (this.options.config.eventType === '1') {
        // eslint-disable-next-line no-new-func
        new Function(`return ${this.options.config.customJs}`)()
      }
      this.loading = true
      this.$refs.generateForm.getData().then(data => {
        if (this.beanId) {
          data.id = this.beanId
        }
        saveGenerate({code: this.code, data: JSON.stringify(data)}).then(({data}) => {
          this.visible = false
          this.loading = false
          this.$message.success(data)
          this.$emit('refreshDataList')

          // 自定义js 保存后执行
          if (this.options.config.eventType === '2') {
            // eslint-disable-next-line no-new-func
            new Function(`return ${this.options.config.customJs}`)()
          }
        })
      }).catch(e => {
      })
    }
  }
}
</script>
